<template>
  <div class="container">
    <div class="userinfo.userinfo" @click='login'>
      <img :src="userinfo.avatarUrl" alt="">
      <p>{{userinfo.nickName}}</p>
    </div>
    <YearProgress></YearProgress>
    <button  @click='scanBook' class='btn'>添加图书</button>
    <button open-type="getUserInfo" lang="zh_CN" @getuserinfo="doLogin">获取用户信息</button>
  </div>
</template>

<script>
import qcloud from 'wafer2-client-sdk'
import config from '@/config'
import {showSuccess, showModal, post} from '@/util'
import YearProgress from '@/components/YearProgress'
export default {
  components: {
    YearProgress
  },
  data () {
    return {
      userinfo: {
        // avatarUrl: '',
        // nickName: '点击登录'
      }
    }
  },
  methods: {
    async addBook (isbn) {
      console.log(isbn)
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openId
      })
      // if (res.code === 0 && res.data.title) {
      showSuccess('添加成功', `${res.data.title}添加成功`)
      // }
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          console.log(res)
          if (res.result) {
            this.addBook(res.result)
          }
        }
      })
    },
    doLogin: function () {
      const session = qcloud.Session.get()
      qcloud.setLoginUrl(config.loginUrl)
      if (session) {
        // 第二次登录
        // 或者本地已经有登录态
        // 可使用本函数更新登录态
        qcloud.loginWithCode({
          success: res => {
            // console.log(res)
            wx.setStorageSync('userinfo', res)
            showSuccess('登录成功')
          },
          fail: err => {
            // console.error(err)
            showModal('登录错误', err.message)
          }
        })
      } else {
        // 首次登录
        qcloud.login({
          success: res => {
            // this.setData({ userInfo: res, logged: true })
            wx.setStorageSync('userinfo', res)
            this.userinfo = res
            showSuccess('登录成功')
          },
          fail: err => {
            console.error(err)
            showModal('登录错误1', err.message)
          }
        })
      }
      this.userinfo = wx.getStorageSync('userinfo')
    }
  },
  onShow () {
    let userInfo = wx.getStorageSync('userinfo')
    // _this.setData({
    this.userinfo = userInfo
    // console.log(userInfo)
    // })
  }
}
</script>

<style lang='scss'>
.container{
  padding:0 30rpx;

}  
.userinfo{
  margin-top:100rpx;
  text-align:center;
  img{
    width: 150rpx;
    height:150rpx;
    margin: 20rpx;
    border-radius: 50%;
  }
}
</style>
